package org.csu.onlineedubackend.controller;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import org.csu.onlineedubackend.entity.Conversation;
import org.csu.onlineedubackend.entity.User;
import org.csu.onlineedubackend.entity.ChatMessage;
import org.csu.onlineedubackend.entity.ChatGroup;
import org.csu.onlineedubackend.mapper.ConversationMapper;
import org.csu.onlineedubackend.mapper.ChatGroupMapper;
import org.csu.onlineedubackend.result.CommonResponse;
import org.csu.onlineedubackend.service.ChatService;
import org.csu.onlineedubackend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.HashMap;

@RestController
@RequestMapping("/api/chat")
public class ChatController {

    @Autowired
    private ChatService chatService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private ConversationMapper conversationMapper;
    
    @Autowired
    private ChatGroupMapper chatGroupMapper;

    private Integer getUserIdFromRequest(HttpServletRequest request) throws NotLoginException {
        try {
            return StpUtil.getLoginIdAsInt();
        } catch (NotLoginException e) {
            String token = request.getHeader("satoken");
            if (token == null || token.isEmpty()) {
                token = request.getParameter("token");
            }
            if (token != null && !token.isEmpty()) {
                Object loginId = StpUtil.getLoginIdByToken(token);
                if (loginId != null) {
                    return Integer.parseInt(loginId.toString());
                }
            }
            throw new NotLoginException("未登录或登录已过期，请重新登录", e.getType(), e.getLoginType());
        }
    }

    /**
     * 获取所有会话列表
     */
    @GetMapping("/all-conversations")
    public CommonResponse<List<Map<String, Object>>> getAllConversations() {
        try {
            // 获取所有会话
            List<Conversation> conversations = conversationMapper.findAll();
            List<Map<String, Object>> result = new ArrayList<>();
            
            // 处理每个会话，添加额外信息
            for (Conversation conversation : conversations) {
                // 使用与getUserConversations相同的逻辑处理会话数据
                Map<String, Object> conversationData = new HashMap<>();
                conversationData.put("conversation", conversation);
                
                // 根据会话类型获取不同的信息
                if ("GROUP".equals(conversation.getType())) {
                    // 获取群组信息
                    try {
                        // 直接使用ChatGroupMapper获取群组信息
                        ChatGroup chatGroup = chatGroupMapper.findByConversationId(conversation.getId());
                        if (chatGroup != null) {
                            conversationData.put("group", chatGroup);
                            conversationData.put("title", chatGroup.getName());
                            conversationData.put("avatar", chatGroup.getName() != null ? 
                                    chatGroup.getName().substring(0, 1) : "G");
                        } else {
                            // 如果群组信息不存在，设置默认值
                            conversationData.put("title", "群聊 #" + conversation.getId());
                            conversationData.put("avatar", "G");
                        }
                    } catch (Exception e) {
                        // 如果获取群组信息失败，设置默认值
                        conversationData.put("title", "群聊 #" + conversation.getId());
                        conversationData.put("avatar", "G");
                    }
                } else if ("PRIVATE".equals(conversation.getType())) {
                    // 对于私聊，设置一些默认值
                    conversationData.put("title", "私聊 #" + conversation.getId());
                    conversationData.put("avatar", "P");
                }
                
                result.add(conversationData);
            }
            
            return CommonResponse.createForSuccess(10000, "获取所有会话成功", result);
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        } catch (Exception e) {
            return CommonResponse.createForError("获取会话列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户的所有会话
     */
    @GetMapping("/conversations")
    public CommonResponse<List<Map<String, Object>>> getUserConversations(
            @RequestParam Integer userId
    ) {
        try {
            List<Map<String, Object>> conversations = chatService.getUserConversations(userId);
            return CommonResponse.createForSuccess(10000, "获取会话列表成功", conversations);
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }

    /**
     * 获取会话的消息历史
     */
    @GetMapping("/messages/{conversationId}")
    public CommonResponse<List<ChatMessage>> getConversationMessages(
            @PathVariable Long conversationId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam Integer userId) {
        try {
            List<ChatMessage> messages = chatService.getConversationMessages(conversationId, userId, page, size);
            return CommonResponse.createForSuccess(10000, "获取消息历史成功", messages);
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }

    /**
     * 创建私聊会话
     */
    @PostMapping("/conversation/private")
    public CommonResponse<Map<String, Object>> createPrivateConversation(
            @RequestBody Map<String, Integer> requestBody,
            @RequestParam Integer userId) {
        
        Integer targetUserId = requestBody.get("targetUserId");
        if (targetUserId == null) {
            return CommonResponse.createForError("目标用户ID不能为空");
        }
        
        try {
            Integer currentUserId = userId;
            Conversation conversation = chatService.createPrivateConversation(currentUserId, targetUserId);
            
            // 获取会话详情
            List<Map<String, Object>> conversations = chatService.getUserConversations(currentUserId);
            for (Map<String, Object> conv : conversations) {
                Conversation c = (Conversation) conv.get("conversation");
                if (c.getId().equals(conversation.getId())) {
                    return CommonResponse.createForSuccess(10000, "获取或创建私聊会话成功", conv);
                }
            }
            return CommonResponse.createForError("无法获取会话详情");
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }

    /**
     * 创建群聊会话
     */
    @PostMapping("/conversation/group")
    public CommonResponse<Map<String, Object>> createGroupConversation(
            @RequestBody Map<String, Object> requestBody,
            @RequestParam Integer userId) {
        
        String groupName = (String) requestBody.get("groupName");
        @SuppressWarnings("unchecked")
        List<Integer> memberIds = (List<Integer>) requestBody.get("memberIds");
        
        if (groupName == null || groupName.trim().isEmpty()) {
            return CommonResponse.createForError("群名称不能为空");
        }
        
        if (memberIds == null || memberIds.isEmpty()) {
            return CommonResponse.createForError("群成员不能为空");
        }
        
        try {
            Conversation conversation = chatService.createGroupConversation(groupName, userId, memberIds);
            
            List<Map<String, Object>> conversations = chatService.getUserConversations(userId);
            for (Map<String, Object> conv : conversations) {
                Conversation c = (Conversation) conv.get("conversation");
                if (c.getId().equals(conversation.getId())) {
                    return CommonResponse.createForSuccess(10000, "创建群聊会话成功", conv);
                }
            }
            return CommonResponse.createForError("创建群聊失败");
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }

    /**
     * 标记会话为已读
     */
    @PostMapping("/read/{conversationId}")
    public CommonResponse<Void> markAsRead(
            @PathVariable Long conversationId,
            @RequestParam Integer userId) {
        try {
            chatService.markAsRead(conversationId, userId);
            return CommonResponse.success();
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }

    /**
     * 获取会话参与者
     */
    @GetMapping("/participants/{conversationId}")
    public CommonResponse<List<User>> getConversationParticipants(
            @PathVariable Long conversationId,
            HttpServletRequest request) {
        try {
            getUserIdFromRequest(request); // check login
            List<User> participants = chatService.getConversationParticipants(conversationId);
            return CommonResponse.createForSuccess(10000, "获取群成员列表成功", participants);
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }

    /**
     * 添加用户到群聊
     */
    @PostMapping("/group/{groupId}/add/{userId}")
    public CommonResponse<Void> addUserToGroup(
            @PathVariable Long groupId, 
            @PathVariable Integer userId,
            HttpServletRequest request) {
        try {
            getUserIdFromRequest(request); // check login
            chatService.addUserToGroup(groupId, userId);
            return CommonResponse.success();
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }

    /**
     * 退出群聊
     */
    @PostMapping("/group/{groupId}/exit")
    public CommonResponse<Boolean> exitGroup(@PathVariable Long groupId,
                                             @RequestParam Integer userId) {
        try {
            Integer currentUserId = userId;
            chatService.removeUserFromGroup(groupId, currentUserId);
            return CommonResponse.createForSuccess(10000, "已退出群聊", true);
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        } catch (RuntimeException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }

    /**
     * 获取用户列表（所有用户）
     */
    @GetMapping("/users")
    public CommonResponse<List<User>> getUsers(@RequestParam(required = false) String token, HttpServletRequest request) {
        // 打印所有请求头，用于调试
        System.out.println("用户列表请求头信息:");
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            System.out.println(headerName + ": " + request.getHeader(headerName));
        }
        
        Integer userId;
        try {
            userId = StpUtil.getLoginIdAsInt();
            System.out.println("获取用户列表，当前用户ID: " + userId);
        } catch (NotLoginException e) {
            // 尝试从请求头中获取token
            String headerToken = request.getHeader("satoken");
            if (headerToken != null && !headerToken.isEmpty()) {
                try {
                    System.out.println("从请求头中获取到token: " + headerToken);
                    Object loginIdObj = StpUtil.getLoginIdByToken(headerToken);
                    if (loginIdObj != null) {
                        userId = Integer.parseInt(loginIdObj.toString());
                        System.out.println("从请求头token获取到用户ID: " + userId);
                        
                        // 获取所有用户
                        List<User> users = userService.list();
                        System.out.println("获取到用户列表，共 " + users.size() + " 个用户:");
                        for (User user : users) {
                            System.out.println("用户ID: " + user.getId() + ", 用户名: " + user.getUsername() + ", 姓名: " + user.getName() + ", 角色: " + user.getRole());
                        }
                        
                        return CommonResponse.createForSuccess(
                                10000, // 使用10000作为成功状态码
                                "获取用户列表成功",
                                users
                        );
                    } else {
                        System.out.println("请求头token无效，未能获取用户ID");
                    }
                } catch (Exception ex) {
                    System.out.println("请求头token验证失败: " + ex.getMessage());
                }
            }
            
            // 尝试从token参数获取用户ID
            System.out.println("Sa-Token认证失败: " + e.getMessage());
            
            if (token != null && !token.isEmpty()) {
                try {
                    System.out.println("尝试验证请求参数中的token: " + token);
                    Object loginIdObj = StpUtil.getLoginIdByToken(token);
                    if (loginIdObj != null) {
                        userId = Integer.parseInt(loginIdObj.toString());
                        System.out.println("从参数token获取到用户ID: " + userId);
                    } else {
                        System.out.println("token参数无效，未能获取用户ID");
                        return CommonResponse.createForError("无法通过token参数获取用户ID");
                    }
                } catch (Exception ex) {
                    System.out.println("Token参数验证失败: " + ex.getMessage());
                    return CommonResponse.createForError("token验证失败: " + ex.getMessage());
                }
            } else {
                System.out.println("没有找到有效的token，返回错误");
                return CommonResponse.createForError("未登录或登录已过期，请重新登录");
            }
        }
        
        // 获取所有用户
        List<User> users = userService.list();
        System.out.println("获取到用户列表，共 " + users.size() + " 个用户:");
        for (User user : users) {
            System.out.println("用户ID: " + user.getId() + ", 用户名: " + user.getUsername() + ", 姓名: " + user.getName() + ", 角色: " + user.getRole());
        }
        
        return CommonResponse.createForSuccess(
                10000, // 使用10000作为成功状态码
                "获取用户列表成功",
                users
        );
    }
    
    /**
     * 删除临时会话
     */
    @DeleteMapping("/conversation/{conversationId}")
    public CommonResponse<Boolean> deleteConversation(
            @PathVariable Long conversationId,
            @RequestParam Integer userId) {
        try {
            boolean success = chatService.deleteConversation(conversationId, userId);
            if (success) {
                return CommonResponse.createForSuccess(10000, "删除会话成功", true);
            } else {
                return CommonResponse.createForError("无法删除会话，您可能不是该会话的参与者");
            }
        } catch (Exception e) {
            return CommonResponse.createForError("删除会话失败: " + e.getMessage());
        }
    }

    /**
     * 加入群聊
     */
    @PostMapping("/group/{groupId}/join")
    public CommonResponse<Void> joinGroup(
            @PathVariable Long groupId,
            @RequestParam Integer userId) {
        try {
            // 调用添加用户到群聊的方法
            chatService.addUserToGroup(groupId, userId);
            return CommonResponse.createForSuccess(10000, "已成功加入群聊", null);
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        } catch (Exception e) {
            return CommonResponse.createForError("加入群聊失败: " + e.getMessage());
        }
    }
} 